package com.eshipenet.shipnet.equipmentextbuilder

import com.github.nscala_time.time.Implicits._

object EquipmentActionPurifier {
  def apply(action: EquipmentAction,
            state: Option[EquipmentAction]): (Option[EquipmentAction], Option[EquipmentAction]) = {
    if (state.isEmpty) {
      action match {
        case a: EquipmentInsert =>
          (Some(a), Some(a))
        case a: EquipmentUpdate =>
          (Some(a), Some(a))
        case a: EquipmentDelete =>
          (Some(a), Some(a))
      }
    } else {
      val currentTs = state.get.actionInfo.timestamp
      action match {
        case a @ EquipmentInsert(_, _, act) =>
          if (act.timestamp >= currentTs) {
            (Some(a), Some(a))
          } else {
            (None, state)
          }
        case a @ EquipmentUpdate(_, _, _, act) =>
          if (act.timestamp >= currentTs) {
            (Some(a), Some(a))
          } else {
            (None, state)
          }
        case a @ EquipmentDelete(_, _, act) =>
          if (act.timestamp >= currentTs) {
            (Some(a), Some(a))
          } else {
            (None, state)
          }
      }
    }
  }
}
